package com.sanjiahantang.ythshopping.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.MainActivity;
import com.sanjiahantang.ythshopping.activity.SearchActivity;
import com.sanjiahantang.ythshopping.activity.me.JsWebActivity;
import com.sanjiahantang.ythshopping.activity.me.NewAreaListActivity;
import com.sanjiahantang.ythshopping.activity.me.SelectAreaActivity;
import com.sanjiahantang.ythshopping.adapter.home.NearbyAdapter;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.model.Area;
import com.sanjiahantang.ythshopping.model.AreaBean;
import com.sanjiahantang.ythshopping.model.MainNearByPageData;
import com.sanjiahantang.ythshopping.model.MainNearByPageModel;
import com.sanjiahantang.ythshopping.presenter.MainNearByPresenter;
import com.sanjiahantang.ythshopping.qrzxing.CaptureActivity;
import com.sanjiahantang.ythshopping.utils.Utils;
import com.sanjiahantang.ythshopping.views.MainNearByView;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by admin on 2017/8/22.
 */

public class MainNearbyFragment extends BaseFragment implements MainNearByView, TextWatcher {

    private SwipeRefreshLayout refreshLayout;
    private boolean isFreshing;
    private RecyclerView mRecyclerView;
    private RecyclerView.OnScrollListener scrollListener;

    private View rootView;
    private TextView city;
    protected  View titelv;
    private View lineLaySearch,txtScanning,ivTitle;
    private LinearLayoutManager layoutManager;
    private NearbyAdapter adapter;
    private MainNearByPresenter presenter;
    private MainNearByPageData pageData;
    private List<Integer> typeList = new ArrayList<>();

    private TextView txtHint;
    private EditText editSearch;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_nearby_main, container, false);
        }

        return rootView;
    }


    @Override
    protected void initView() {

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.nearbyRecyV);
        layoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(layoutManager);
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.nearby_page_refresh);
        presenter = new MainNearByPresenter(this);
        city = (TextView) rootView.findViewById(R.id.txtMessage);
        txtScanning = rootView.findViewById(R.id.txtScanning);
        lineLaySearch = rootView.findViewById(R.id.lineLaySearch);
        txtHint = (TextView) rootView.findViewById(R.id.txtHint);
        editSearch = (EditText) rootView.findViewById(R.id.editSearch);
        ivTitle = rootView.findViewById(R.id.title);

        txtHint.setVisibility(View.GONE);
        editSearch.setVisibility(View.VISIBLE);
        titelv= rootView.findViewById(R.id.nearby_top);
        titelv.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.bg_sousuo));
        city.setOnClickListener(this);
        txtScanning.setOnClickListener(this);
//        lineLaySearch.setOnClickListener(this);
        ivTitle.setOnClickListener(this);
        editSearch.addTextChangedListener(this);



        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                System.gc();
                if (isFreshing) {
                    return;
                } else {
                    refreshLayout.setRefreshing(true);
                    isFreshing = true;
                    onResume();
                }
            }
        });

        scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }
        };
    }

    @Override
    protected void initData() {
        super.initData();

    }

    private void setCity(){
        if (ConfigValue.currentCity == null){
            city.setText("北京");
        }else {
            city.setText(ConfigValue.currentCity.getRegion_name());
        }
    }

    @Override
    protected void initTitle() {

    }

    @Override
    public void getData(MainNearByPageModel response) {

        refreshLayout.setRefreshing(false);
        isFreshing = false;

        if(response!=null)
        {
            if (response.getCode().equals("200")) {

                pageData = response.getData();
                ConfigValue.rid = pageData.getArea();

                typeList.clear();
                for (int i = 1; i < 4; i++) {
                    typeList.add(i);
                }
                adapter = new NearbyAdapter(context,typeList  ,pageData, (MainActivity) getActivity());
                mRecyclerView.setLayoutManager(layoutManager);
                mRecyclerView.setAdapter(adapter);
            } else {
                Log.d("NEAR_BY_FRAGMENT", "response: ");
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.txtScanning:
                if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(getContext())) {
                    return;
                }
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);

                } else {
                    Intent itCapture = new Intent(getActivity(), CaptureActivity.class);
                    itCapture.putExtra("type","home");
                    startActivity(itCapture);

                }


                break;

            case R.id.txtMessage:
                Intent it = new Intent(context,NewAreaListActivity.class);
                it.putExtra("from","main");
                startActivityForResult(it, 1);
                break;

            case R.id.lineLaySearch:
                Intent search = new Intent(context, SearchActivity.class);
                startActivity(search);
                break;

            case R.id.title:
                doSearch();
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1)
        {
            if (resultCode==2)
            {
                ConfigValue.currentCity = new Gson().fromJson(data.getStringExtra("city"), AreaBean.City.class);

                ConfigValue.rid = ConfigValue.currentCity.getRegion_id();
                city.setText(ConfigValue.currentCity.getRegion_name());

//                presenter.getMainNearByPageData(context);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setCity();
        presenter.getMainNearByPageData(context);
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("onPause", "onPause: ");
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.toString().contains("\n")){
            editSearch.setText(s.subSequence(0,s.length() - 1));
            doSearch();
        }
    }

    private void doSearch(){
        String searchContent = editSearch.getText().toString();
        if(searchContent.length() > 0){
            Intent intentjs = new Intent(context, JsWebActivity.class);
            intentjs.putExtra("url", "mobile/lmshop.php?act=shop_three&keyword="
                    + URLDecoder.decode(searchContent)
                    + "&from_app=2&key=" + ConfigValue.DATA_KEY);
//                    + "&rid=" + ConfigValue.rid);
            ((MainActivity)context).startActivityForResult(intentjs,MainActivity.RESULT_NEAR);
            editSearch.setText("");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
